package org.dangran.util;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ListToPage {

    /**
     * 集合分页
     *
     * @param list     集合
     * @param pageNum  当前页
     * @param pageSize 每页大小
     * @return T
     */
    public static <T> Page<T> listToPage(List<T> list, int pageNum, int pageSize) {
        int total = list.size();
        int pageSum = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
        //适合小数据量 <1000
//        List<T> record = list.subList((pageNum - 1) * pageSize, Math.min(total, pageNum * pageSize));
        //适合小数据量 >10000
        List<T> record = list.stream()
                .skip((long) (pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        Page<T> page = new Page<>();
        page.setRecords(record);
        page.setPages(pageSum);
        page.setTotal(total);
        page.setCurrent(pageNum);
        page.setSize(pageSize);
        return page;
    }

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "a", "b", "c", "d", "e", "f", "g", "h", "i","j","k","l","m","n");
        list.forEach(System.out::print);

        Page<String> page = listToPage(list, 2, 10);
        System.out.println("\n========================");
        System.out.println(page.getRecords());
    }
}
